package com.qyhl.webtv.basiclib.utils.network.Other;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by android1 on 2018/1/18.
 */

public abstract class HttpCallback<T> implements Observer<BaseBean<T>> {
    protected abstract void success(BaseBean<T> bean);

    public abstract void failure(int code, String msg);

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseBean<T> bean) {
        if (bean != null) {
            //在这里可以根据协议添加限制条件,比如返回字段中某一字段必须为多少，但必须T继承自某一公共基类
            if (bean.getCode() == 200) {
                success(bean);
            } else {
                failure(bean.getCode(), bean.getMessage());
            }
        } else {
            failure(-2, "请求出错！");
        }
    }

    @Override
    public void onError(Throwable e) {
        if (e.toString().contains("timeout")) {
            failure(-3, "请求超时，请求失败！");
        } else if (e.toString().contains("502")) {
            failure(-3, "服务器异常，请求失败！");
        } else if (e.toString().contains("Failed to connect to")) {
            failure(-3, "网络异常，请求失败，请检查您的网络！");
        } else {
            failure(-3, "解析数据异常，请求失败！");
        }

    }

    @Override
    public void onComplete() {

    }
}
